# -*- coding: utf-8 -*-

"""
@author: 猿小天
@contact: QQ:1638245306
@Created on: 2021/6/3 003 0:30
@Remark: 字典管理
"""
import json

from rest_framework import serializers

from dvadmin.system.models import SysDict
from dvadmin.system.util.log_helper import SetLog
from dvadmin.utils.json_response import SuccessResponse, ErrorResponse, DetailResponse
from dvadmin.utils.redis_helper import RedisHelper
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.string_util import str2bool
from dvadmin.utils.viewset import CustomModelViewSet


class SysDictSerializer(CustomModelSerializer):
    """
    字典-序列化器
    """

    class Meta:
        model = SysDict
        fields = "__all__"
        read_only_fields = ["id"]


class SysDictCreateUpdateSerializer(CustomModelSerializer):
    """
    字典管理 创建/更新时的列化器
    """

    class Meta:
        model = SysDict
        fields = '__all__'


class SysDictTreeSerializer(CustomModelSerializer):
    """
    字典表的树形序列化器
    """
    children = serializers.SerializerMethodField(read_only=True)

    def get_children(self, instance):
        queryset = SysDict.objects.filter(up=instance.id).filter(status=1)
        if queryset:
            serializer = SysDictTreeSerializer(queryset, many=True)
            return serializer.data
        else:
            return None

    class Meta:
        model = SysDict
        fields = "__all__"
        read_only_fields = ["id"]


class SysDictViewSet(CustomModelViewSet):
    """
    字典管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = SysDict.objects.all()
    serializer_class = SysDictSerializer
    # extra_filter_backends = []
    # permission_classes = []
    filter_fields = ['up_id', 'name', 'memo']
    search_fields = ['name', 'memo']

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data, request=request)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        '''
            写入redis 
            key规则为 setting:sysdic:id
        '''
        key = ":".join(['setting', 'sysdic', str(serializer.data.get('id', '-1'))])
        value = dict(id=serializer.data.get('id', '-1'), name=serializer.data.get('name', ''),
                     value=serializer.data.get('value', ''), memo=serializer.data.get('memo', ''))
        RedisHelper.set(key, json.dumps(value))
        verbose_name = serializer.Meta.model._meta.original_attrs['verbose_name']
        SetLog(request, '%s 用户新增[%s]数据.' % (request.user.username, verbose_name), memo=request.data)
        return DetailResponse(data=serializer.data, msg="新增成功")

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, request=request, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        '''
            更新后写入redis 
            key规则为 setting:sysdic:id
            先移除redis，再重新写入
        '''
        key = ":".join(['setting', 'sysdic', str(serializer.data.get('id', '-1'))])
        value = dict(id=serializer.data.get('id', '-1'), name=serializer.data.get('name', ''),
                     value=serializer.data.get('value', ''), memo=serializer.data.get('memo', ''))
        RedisHelper.delete(key)
        RedisHelper.set(key, json.dumps(value))

        verbose_name = serializer.Meta.model._meta.original_attrs['verbose_name']
        SetLog(request, '%s 用户修改[%s]数据.' % (request.user.username, verbose_name), memo=request.data)
        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}
        return DetailResponse(data=serializer.data, msg="更新成功")

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        key = ":".join(['setting', 'sysdic', str(instance.id)])
        self.perform_destroy(instance)
        '''
            删除后，移除redis 
            key规则为 setting:sysdic:id
        '''
        RedisHelper.delete(key)
        verbose_name = instance._meta.original_attrs['verbose_name']
        SetLog(request, '%s 用户删除[%s]数据.' % (request.user.username, verbose_name), memo=request.data)
        return DetailResponse(data=[], msg="删除成功")

    def set_dict_enable(self, request, *args, **kwargs):
        '''
            设定字典是否启用
            enable：启用 true；禁用 false；
        '''
        instance = SysDict.objects.filter(id=kwargs.get('pk')).first()
        data = request.data
        enable = data.get('enable')
        if not enable is None:
            enable = str2bool(enable)
        else:
            enable = True
        if instance:
            instance.status = enable
            instance.save()
            SetLog(request, '%s 修改字典项目启用状态' % request.user.username)
            return DetailResponse(data=None, msg="修改成功")
        else:
            return ErrorResponse(msg="字典数据不存在")
